/*
 * @lc app=leetcode.cn id=71 lang=cpp
 *
 * [71] 简化路径
 */

// @lc code=start
class Solution
{
public:
  string simplifyPath(string path)
  {
    stack<string> stack;
    int n = path.size();
    int L = 0;
    while (L < n) {
      // skip all continuous '/'
      while (L < n && path[L] == '/')
        ++L;
      int R = L;
      string filename;
      while (R < n && path[R] != '/')
        filename.push_back(path[R++]);
      if (filename == "..") {
        if (!stack.empty())
          stack.pop();
      }
      else if (filename.size() > 0 && filename != ".")
        stack.push(filename);
      L = R;
    }
    if (stack.empty())
      return "/";
    string ans;
    do {
      ans = "/" + stack.top() + ans;
      stack.pop();
    } while (!stack.empty());
    return ans;
  }
};
// @lc code=end
